<?php 
namespace Wdl\model;
use Wdl\helper\VillageHelper;
use Wdl\helper\webHelper;

class showhouse extends base{

    public function index()
    {
        $house = new house($this->app);
        $uniacid = $this->uniacid;
        $uid =  $this->uid;
        $openid = $this->openid;
        $id = $this->_GPC['id'];
        $_GPC = $this->_GPC;
        $fileds = '*, 0+CAST(loyer AS CHAR) as loyer ';
        $sql = "SELECT $fileds  FROM " . tablename("kbwdl_house") . " where uniacid='$uniacid' and  id='$id'";
        $info = pdo_fetch($sql);
        if(empty($info)){
            /*没有获取到数据不操作*/
            return  $this->msg(0, '', []);
        }
        /* 处理房源信息 获取腾讯实际播放地址 */
        preg_match('/<iframe(.*?)src="(.*?)"/', $info['description'], $arr);
        $info['vurl'] = $arr[2];
        $urlinfo = parse_url($arr[2]);
        if(!empty($urlinfo['query'])){
            $query = explode('&', $urlinfo['query']);
             $a2 = array();
                foreach ($query as $q)
                {
                    $a1 = explode('=', $q);
                    $a2[$a1[0]] = $a1[1];
                }
        }
        $info['videoid'] = $a2['vid'];
        $furl_real = '';
        if(!empty($info['videoid'])){
           $a3 = file_get_contents('https://vv.video.qq.com/getinfo?otype=json&appver=3.2.19.333&platform=11&defnpayver=1&vid='.$info['videoid']);
            // $a3 = file_get_contents('http://vv.video.qq.com/getinfo?vids='.$info['videoid'].'&platform=101001&charge=0&otype=json');
            $a3  = str_replace('QZOutputJson=', '', rtrim($a3,';'));
            $a3 = json_decode($a3, true);
            $fvkey = $a3['vl']['vi'][0]['fvkey'];
            $fn = $a3['vl']['vi'][0]['fn'];
            $furl = $a3['vl']['vi'][0]['ul']['ui'][0]['url'];
            $furl_real = $furl .$fn .'?vkey='.$fvkey;
        }
        $info['videoinfo'] = $furl_real;
        /* 结束腾讯视频获取 */
       /*获取自己上传的视频*/
        if(!empty($info['video']) ){
            $info['video'] = tomedia($info['video']);           
        }else{
            $info['video'] = '';
        } 
        /*封面图*/
        if(empty($info['thumb'])){
            $info['thumb'] =  'addons/kbwdl_shequzufang/style/images/house_face.jpg' ;
        }
        if (!empty($info['thumb_url'])) {
            $info['thumbs'] = iunserializer($info['thumb_url']);
            foreach ($info['thumbs'] as $key => $item) {
                $info['thumbs'][$key] = tomedia($item);
            }           
        }
        if (empty($info['thumbs'])) {
             /*把封面图加载进来*/
            $info['thumbs'][] = tomedia( $info['thumb']) ;           
        }
        /*兼容 重新组装 thumbs 数据 兼容 幻灯片组件*/
        foreach($info['thumbs'] as $thumb){
            $info['slides'][] = array(
                'url'=> "",/*这个是图片链接*/
                'thumb'=> $thumb,
            );
        }
        /**户型图 */
        $info['hximgs'] = [];
        if($info['thumb_struct']){
            $info['thumb_struct'] = iunserializer($info['thumb_struct']);
            foreach ($info['thumb_struct'] as $key => &$item) {
                $item = tomedia($item) ;
                $info['hximgs'][] = ['url'=> '', 'thumb'=> $item];
            }    
        }
         /*默认封面图*/
        $info['update_time'] = date('Y-m-d H:i:s', $info['update_time']);
        $params = pdo_fetchall("select * from ".tablename("kbwdl_param")." where houseid='$id' order by displayorder asc");
        foreach($params as $k => $p){
            $info['params'][] = $p;
        } 
             /**联系人信息*/
        $default_avatar = "/addons/kbwdl_shequzufang/style/images/get_avatar.png";
        $info['broker'] = array(
            'id' => 0,
            'avatar' => toimage($default_avatar),
            'nickname'=> $info['publish_name'],
            'mobile'=> $info['linkphone'],
            'company'=> '联系人',
        );
        /* 获取经济人 */
        $info['orgin_broker_id'] = $info['broker_id']; /*房源发布人的真实人*/
        $isremobile = 1;
        /*如果有指定经纪人 id 那么把发布人替换成此人 主要是海报分享扫码进来*/
        if(isset($_GPC['brokerid']) && (intval($_GPC['brokerid'])>0)){             
            $info['broker_id'] = intval($_GPC['brokerid']);
            $isremobile = 0;
        }
        if ($info['broker_id']) {
            $broker = pdo_fetch("select * from " . tablename("kbwdl_broker") . " where  id='" . $info['broker_id'] . "'");
        }else{
            //随机取一个
            $broker = pdo_fetch("select * from " . tablename("kbwdl_broker") . " where iscompany=1 and uniacid='$uniacid' ORDER BY RAND()");
        }
        if($broker){
            if (!strpos($broker['avatar'], "/")) {
                $broker['avatar'] = $default_avatar;
            }
            $broker['nickname'] = !empty($broker['truename']) ? $broker['truename']: $broker['nickname'];
            $broker['avatar'] = toimage($broker['avatar']);            
            $info['broker'] = $broker;
        }
        /*格式化数据*/
        $info = $house->_format_sechouse($info);
        if($this->app->module['config']['isduocity']==1){
            $info['area'] = $info['cityname'].'-'.$info['area'];
        }
        /*修正百度地图到腾讯地图*/
        $info['longitude'] = 0;
        $info['latitude'] = 0;
     
      if(strlen($info['mapinfo'])>2){
         /*百度坐标转换为火星坐标 腾讯地图显示火星坐标*/  
          $info['mapinfo'] = VillageHelper::baidu_map_txmap($info['mapinfo']);
          $m = explode(",", $info['mapinfo']);
          $info['longitude'] = $m[0];
          $info['latitude'] = $m[1];
               
      }
        /*点击数*/
        if($id){
            pdo_update( 'kbwdl_house', array('onclick +='=>1) , array('id' => $id) ); 
        }
        /**判断是否收藏 */
        $info['isfavorite'] = 0;
        $where =  ['houseid'=> $id, 'acttype'=> 'fav', 'uniacid'=> $uniacid, 'openid'=> $openid];
        $fav = pdo_fetch("select id from " . tablename("kbwdl_favorite") .
                " where hits=1 AND  houseid=:houseid AND acttype=:acttype  AND  uniacid=:uniacid AND openid=:openid",
                $where
        );
        if($fav){
            $info['isfavorite'] = 1; //表示收藏
        }
        /*浏览历史记录*/
        $houseid = intval($id);
        $yested = TIMESTAMP-24*3600;
        $fav = pdo_fetch("select id from ".tablename("kbwdl_favorite")." where ftype=1 and addtime>'$yested' and houseid='$houseid' and uniacid='$uniacid' and openid='$openid'");
        if(!empty($fav)){
           pdo_update(
                'kbwdl_favorite',
                array('hits +='=>1,'last_time' => TIMESTAMP,'ftype' => $info['zhutype']) ,
                array('id' => $fav['id'])
            );       
        }else{
            $savedata  = array(
                'uid'=> $uid,
                'openid'=> $openid,
                'uniacid'=> $uniacid,
                'addtime' => TIMESTAMP,
                'houseid' => $houseid,
                'ftype' => $info['zhutype'], //房源类型
                'hits'=>1,
                'acttype'=>'view',
                'last_time' => TIMESTAMP,
                'title' => $info['title'],
                'smalltext' => "{$info['village_name']} | {$info['room']}房{$info['hall']}厅{$info['garder']}卫 | {$info['superficie']}㎡ | {$info['loyer']}{$info['prix_unitaire']}"      
             );
             pdo_insert('kbwdl_favorite', $savedata);
        }
        /**今日访问 */
        $today = date('Ymd');
        $clicks = pdo_fetch("select id from ".tablename('kbwdl_count')."where title=:title and uniacid=:uniacid and stat_type=100 and  house_type=:house_type", 
            ['title'=> $today, 'uniacid'=> $uniacid,'house_type'=> $info['zhutype']]);
        if($clicks){
            pdo_query("update ".tablename('kbwdl_count')." set nums=nums+1  where id=:id",['id'=> $clicks['id']]);
        }else{
            pdo_insert("kbwdl_count", ['title'=> $today, 'uniacid'=> $uniacid,'stat_type'=>100,'nums'=>1 ,'house_type'=>$info['zhutype']]);
        }
        /*查询房源的小区数据*/
        $info['village'] = null;
        if($info['village_id'] && $info['zhutype'] < 4){
            $village = pdo_fetch("select * from ".tablename("kbwdl_area")." WHERE id=:id",['id'=>$info['village_id']]);
            if($village){
                //求均价
               $sum =  pdo_fetch("select sum(loyer) as loyer,sum(superficie) as sf from ".tablename("kbwdl_house").
                    " WHERE village_id=:vid AND uniacid=:uniacid AND zhutype=:zhutype",
                ['uniacid'=> $info['uniacid'],'zhutype'=>$info['zhutype'], 'vid'=> $info['village_id']]);
                if($sum){
                    $village['item_per'] = ceil( $sum['loyer'] * 10000 / max(1, $sum['sf']) ) . "元/㎡";
                }

                if($village['point']){
                    $village['point'] = VillageHelper::baidu_map_txmap($village['point']);
                    // 小区坐标覆盖
                    $m = explode(",", $village['point']);
                    $info['longitude'] = $m[0];
                    $info['latitude'] = $m[1];
                }            
                $village['thumb'] = tomedia($village['thumb']);
                $info['village'] = $village;
                //获取小区的周边配套数据
                $mapdata = webHelper::fetch_place_data('village_mapdata','', $info['village_id']);
                $info['mapdata'] = $mapdata;
            }
           
        }
        $info['newhouse'] = [];
        if($info['zhutype'] ==3){
            /**新房查询开发商资料 */
            $info['newhouse'] = pdo_fetch("select green,capacity,developer,constructor,
            parking ,roomcount, totalarea, builtuparea,property, propertyprice,public_area from
             ". tablename("kbwdl_house_info")." where fid=:fid ", ['fid'=> $info['id']]);
        }

        
       
       return  $this->msg(0, '', $house->_format_show_item($info));
  
    }


    public function realhouse()
    {
        $house = new house($this->app);
        $uniacid = $this->uniacid;
        $uid =  $this->uid;
        $openid = $this->openid;
        $id = $this->_GPC['id'];
        $village_id = $this->_GPC['village_id']; //通过小区查询关联
        $zhutype = $this->_GPC['zhutype'];
        if($id){
            $info = pdo_fetch("select * from ".tablename("kbwdl_house")." where id=:id", ['id'=>$id]);
        }elseif($village_id){
            $info = pdo_fetch("select * from ".tablename("kbwdl_area")." where id=:id",['id'=> $village_id]);
            $info['village_id'] = $village_id;
            $info['id'] = 0;
            $info['village_name'] = $info['title'];
            $info['zhutype'] = $zhutype ?? 0;
        }
        
        $total = $list = null;

        if($info){
            $condition = " isonline=1 and isdelete=0 AND zhutype=:zhutype AND  id<>:id AND uniacid=:uniacid AND (village_id=:village_id OR village_name=:village_name)";
            $where= [
                'id'=>  $info['id'],
                'village_id'=> $info['village_id'],
                'village_name' => $info['village_name'],
                'uniacid' => $info['uniacid'],
                'zhutype'=> $info['zhutype']
            ];
           
            $total = pdo_fetchcolumn("select count(*) as total from ".tablename("kbwdl_house"). " where $condition ", $where);
            $sql = "select *  from ".tablename("kbwdl_house"). " where $condition order by refresh_time desc,update_time desc   limit 6";
            $list = pdo_fetchall($sql, $where);
            foreach($list as $k => $info){
                $info['thumb'] = tomedia($info['thumb']);
                $list[$k] = $house->_format_show_item($info);
            }
            
        }


        return  $this->msg(0, '',  ['total'=> $total , 'list'=> $list]); 
    }

   
}